﻿namespace DimensionsHelper.ExcelAddIn.Core.Sql;

/// <summary>
/// 字段值记录类
/// </summary>
public class FieldRecord(string fieldName)
{
    private readonly Dictionary<string, Record> _values = new();
    private readonly Dictionary<string, int> _idStorage = new();


    /// <summary>
    /// 字段名称
    /// </summary>
    public string FieldName => fieldName;

    /// <summary>
    /// 当前字段中已记录的所有值数组。
    /// </summary>
    public string[] Values => _values.Keys.ToArray();

    /// <summary>
    /// 当前字段中已记录的所有值的记录数组。
    /// </summary>
    public Record[] Records => _values.Values.ToArray();

    /// <summary>
    /// 获取当前字段中已记录的样本的基数。
    /// </summary>
    public int Base => _idStorage.Count;

    /// <summary>
    /// 向当前字段中添加一个值和样本ID的记录。
    /// </summary>
    /// <param name="value">字段值</param>
    /// <param name="sampleId">样本ID</param>
    /// <returns></returns>
    public bool Add(string value, string sampleId)
    {
        if (!_values.TryGetValue(value, out var record))
        {
            record = new Record(FieldName, value);
            _values.Add(value, record);
        }

        if (_idStorage.TryGetValue(sampleId, out int c))
        {
            _idStorage[sampleId] = c + 1;
        }
        else
        {
            _idStorage.Add(sampleId, 1);
        }

        return record.Add(sampleId);
    }

    /// <summary>
    /// 从当前字段中移除一个值和样本ID的记录。
    /// </summary>
    /// <param name="value">字段值</param>
    /// <param name="sampleId">样本ID</param>
    /// <returns></returns>
    public bool Remove(string value, string sampleId)
    {
        if (!_values.TryGetValue(value, out Record? record))
        {
            return false;
        }

        if (_idStorage.TryGetValue(sampleId, out int count))
        {
            count--;
            if (count == 0)
            {
                _idStorage.Remove(sampleId);
            }
            else
            {
                _idStorage[sampleId] = count;
            }
        }

        return record.Remove(sampleId);
    }

    /// <summary>
    /// 统计当前字段中指定值的样本数。
    /// </summary>
    /// <param name="value">字段值</param>
    /// <param name="weightingMap">样本全指表</param>
    /// <returns></returns>
    public double Count(string value, Dictionary<string, double>? weightingMap = null)
    {
        return _values.TryGetValue(value, out var record) ? record.Count(weightingMap) : 0;
    }
}
